package szhn.config;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import szhn.model.UserModel;

/**
  * 登陆拦截器
 * @author Panxinxing
 * 2020年5月12日
 *
 */
@Configuration
public class LoginInterceptor implements HandlerInterceptor, WebMvcConfigurer {
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		UserModel user = (UserModel) request.getSession().getAttribute("user");
		if(null == user) {
			//若为前后端分离，此处设置HTTP状态为401
			// TODO 加入全局过滤器后需改造此处，用于未登录情况的报错
			response.sendRedirect("login");
			return false;
		}
		
		//可专门抽出一个类来实现用户与url以及method的匹配来实现用户权限与url强关联的权限模式，或者使用shiro
		String url = request.getServletPath();
		String method = request.getMethod();
		//普通用户只能查询，不能增删改操作
		if(!"GET".equals(method) && user.getType() == 1) {
			//此处待补充405状态码
			return false;
		}
		
		return true;
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		// 不过滤URL
		String[] excludeUrls = {"/swagger-ui.html", "/swagger-resources/**", "/webjars/**", "/swagger/**", 
				"/v2/api-docs/**", "/login", "/login/**", "/static/**"};
		registry.addInterceptor(new LoginInterceptor()).addPathPatterns("/**").excludePathPatterns(excludeUrls);
	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 静态资源
		registry.addResourceHandler("/static/**").addResourceLocations("classpath:/static/");
		// 过滤swagger
		registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
		registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
		registry.addResourceHandler("/swagger-resources/**").addResourceLocations("classpath:/META-INF/resources/swagger-resources/");
		registry.addResourceHandler("/swagger/**").addResourceLocations("classpath:/META-INF/resources/swagger*");
		registry.addResourceHandler("/v2/api-docs/**").addResourceLocations("classpath:/META-INF/resources/v2/api-docs/");
	}

}